package com.wgl.express.UI;

import static com.wgl.express.text.Text.*;

import com.wgl.express.entity.Package;
import com.wgl.express.service.Impl.PackageServiceImpl;
import com.wgl.express.service.PackageService;
import com.wgl.express.util.MybatisUtils;
import com.wgl.express.util.Util;

import java.io.IOException;
import java.util.List;



public class App {
    private Util util;

    public App() {
    }

    public void init(){
        util = Util.getUtil();
        if (!checkConnection()) quit();
    }
    public void start(){
        eventLoop();
        quit();
    }

    private void quit() {
        util.say(BYE);
        System.exit(0);
    }

    public void eventLoop(){
        boolean exit = false;
        int choose;
        while (!exit){
            util.say(TITLE);
            util.say(MENU_FIRST);
            if ((choose = util.readInt()) == -1) continue;
            switch (choose){
                case 1:gotoSearchPackage();break;
                case 2:gotoLogin();break;
                case 3:gotoReg();break;
                case 0:exit = true;break;
                default:break;
            }

        }
    }

    private void gotoReg() {
        Register reg = new Register();
        reg.start();
    }

    private void gotoLogin() {
        Login login = new Login();
        login.start();

    }

    private void gotoSearchPackage() {
        PackageService packageService = new PackageServiceImpl(1);
        int pid;

        util.say("请输入快递单号：");
        pid = util.readInt();

        List<Package> packByPid = packageService.getPackByPid(pid);
        if (packByPid.size() == 1){
            util.showPackInfoUnPub(packByPid.get(0));
        }else{
            util.say("查不到此快递！\n");
        }
    }

    public boolean checkConnection(){
        try {
            MybatisUtils.getSqlSession();
            return true;
        } catch (IOException e) {
            util.say("数据库连接失败！");
//            e.printStackTrace();
            return false;
        }
    }


}
